<?php
/**
 * 下单、支付控制器
 */

namespace app\api\controller;
use app\api\server\member\memberServer;
use app\common\common\model\oldModel\coupons\Coupons;
use app\common\common\model\oldModel\goods\Goods;
use app\common\common\model\oldModel\order\OrderItem;
use app\common\common\Server\commonServer;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Validate;

class Pay extends Base
{
    /**
     * 提交订单
     * @param json $goods //商品信息
     * @param string $key 秘钥
     */
    public function order() {

        $key     = input('key');   //密钥
        $storeId = input('store_id'); //门店id
        $storeName= input( 'store_name'); //门店名称
        $token   = input( 'token'); //token
        $goods   = json_decode(input('goods'), true);  //商品信息
        $couponsId  = input('coupons_id'); //优惠券id
        $couponsVal = input('coupons_val'); //优惠券金额
        $tableware  = input('tableware'); //餐具数量
        $payType    = input('pay_type'); //支付类型  1微信  5嘉和卡 25早餐月卡  30共享早餐卡
        $activityVal= input('activity_val'); //营销活动 满减金额， 无校验营销金额是否正确
        $marketing_ids =[];
        $marketing_ids[]= input( 'marketingId');  //营销活动Id

        aw_log( ['input' => Request::instance()->param()  ,'session' =>  $token ]  , 'pay_order.log');
        $type       = input( 'type' ,3); // 订单类型（1：外卖；2：自取；3：堂食）
        $result = $this->validate(
            Request::instance()->param(),
            [
                'key'  => 'require',
                'store_id'  => 'require',
                'goods'     => 'require',
                'tableware' => 'require',
                'pay_type'  => 'require',
                'token'  => 'require',
            ]
        );
        if( true !== $result ){
            // 验证失败 输出错误信息
            commonServer::$showMsg = $result;
            commonServer::error(2)->exits();
        }
        $member_server = new memberServer();
        //验证key合法
        $member_info = $member_server->checkCiphertext($key);
        $member_info['new'] = 1;
        aw_log($member_info, 'tijiao.log');
        if ( $member_info === false ) {
            commonServer::$showMsg = '密钥不合法';
            commonServer::error(2)->exits();
        }

        $redis = getRedis( 1);
        $_token = $redis->get( 'order_token_' .$member_info['id']  );

        if( $_token !== input( '__token__') ){
            commonServer::$showMsg = '请不要重复下单';
            commonServer::error(2)->exits();
        }

        //开启事务
        // Db::startTrans();
        try {
            $memberModel = new \app\common\common\model\member\member();
            $member_new_info = $memberModel->where( array('id' => $member_info['id']) )->field( 'id , open_id ,union_id')->find();
            $member_odl_info = $member_server->getOldMemberByNewId( $member_info['id'] );
            $member_info['old'] = 1;
            aw_log($member_odl_info, 'tijiao.log');
            if( !$member_odl_info ){
                commonServer::$showMsg = '用户不存在或已禁用';
                commonServer::error(2)->exits();
            }
            //订单总价    商品总价      商品数量     商品折扣价格
            $orderPrice = $goodsPrice = $goodsNum = $money_goods_discount = 0;
            $money_half_two = 0; //第二份半价金额
            $orderGoods = [];//订单商品信息
            $goodsModel = new Goods();
            $orderModel = new \app\common\common\model\oldModel\order\order();
            //判断是否可以使用单品
            $goods_tag = 0;
            $wxpay     = 1;  //是否需要调取微信支付  1是 0否
            $dpGoodsList = config( 'site.dp_goodslist');

            //遍历判断商品信息
            foreach ($goods as $item) {
                if( !isset($item['num'])  ||  !isset($item['dishsno']) || !isset($item['tow_half'])  ){
                    commonServer::$showMsg = '参数错误';
                    commonServer::error(2)->exits();
                }
                $goodsInfo = $goodsModel->getGoodsInfo($storeId, $item['dishsno'] , $type);  //获取商品信息
                if (!$goodsInfo) {
                    commonServer::error(30001)->exits();
                }

                if($goodsInfo['status']   != 1 ){
                    commonServer::$showMsg = $goodsInfo['name'] . '已下架';
                    commonServer::error(30001)->exits();
                }
                if($goodsInfo['stock'] <=0 ){
                    commonServer::$showMsg = $goodsInfo['name'] . '已售罄,暂时无法购买~您可以选择其他菜品哦~';
                    commonServer::error(2)->exits();
                }

                $goodsPrice += $goodsInfo['member_price'] * $item['num'];  //商品总价 =  商品会员价格 * 商品数量
                //判断是否第二份半价
                if ( $item['num'] >= 2 && $goodsInfo['second_half'] == 1 ) {
                    $num = floor($item['num'] / 2);
                    $money_half_two += $num * ($goodsInfo['member_price'] / 2);
                }

                //商品总数
                $goodsNum += $item['num'];
                //整理订单商品表数据
                $orderGoods[] = $orderModel->setOrderItemParam( $item , $goodsInfo);

                //商品折扣总价格  =  商品原价 - 商品会员价 * 商品数量
                $money_goods_discount += ($goodsInfo['current_price'] - $goodsInfo['member_price']) * $item['num'];
                $marketing_ids[] =  isset( $item['marketingId'])  ? $item['marketingId'] : 0;

                //判断是否有单品商品
                if( in_array(  $item['dishsno'] , $dpGoodsList) ){
                    $goods_tag = 1;
                }
            }


            //判断有单品商品，且是否存在优惠券
            if( $goods_tag == 1  && $couponsId ){
                commonServer::error(20005)->exits();
            }
            //判断是否有优惠券
            if ( $couponsId && $couponsVal ) {
                //验证优惠券是否可用 , 只校验优惠券是否可用，无校验金额是否正确
                if (!$orderModel->checkCoupons($member_odl_info['member_id'], $couponsId)) {
                    commonServer::error(20005)->exits();
                }
            } else {
                //不可用 或不存在则优惠券金额为0
                $couponsVal = 0;
            }

            $money_tableware = $tableware * config('tableware_price');
            //判断是否有营销活动，没有营销活动则金额为0
            $activityVal = $marketing_ids ? $activityVal : 0;
            $goodsPrice -= $money_half_two; //商品金额 = 商品金额 - 第二份半价金额  + 餐具费
            //订单价格 = 商品价格 - 优惠价格 - 满减活动价格
            $orderPrice = $goodsPrice - $couponsVal - $activityVal + $money_tableware;
            if ( $orderPrice <= 0 ) {
                $orderPrice = 0;
            }
            //保留2位小数
            $orderPrice = round( $orderPrice , 2);

            //验证支付类型 是否满足使用条件
            if(  !$orderModel->checkPayType( $payType  , $member_odl_info['member_id'] , $orderPrice  , $goodsNum , $storeId) ){
                commonServer::$showMsg = $orderModel->error;
                commonServer::error(20004, [], $orderModel->error)->exits();
            }

            //同步旧平台订单金额 展示方式
            if( $payType == 25 || $payType == 30){
                //判断是 早餐卡支付的时候  优惠金额 为 应收金额， 早餐卡不可与优惠券同步使用
                $couponsVal = $orderPrice;
                $orderPrice = 0;
            }

            $orderCode = get_order_code('X');  //订单编号
            $param = [];
            $param['store_id']    = $storeId;
            $param['member_id']   = $member_odl_info['member_id'];
            $param['money_goods'] = $goodsPrice;  //商品总价
            $param['money_goods_discount'] = $money_goods_discount;  //商品折扣价
            $param['money_pay']  = $orderPrice;  //应付价格
            $param['order_code'] = $orderCode;
            $param['money_tableware'] = $money_tableware;  //餐具费 * 数量
            $param['money_coupon']    = $couponsVal;  //优惠券抵扣
            $param['money_reduct']    = $activityVal;  //满减
            $param['coupon_id']       = $couponsId;   //优惠券id
            $param['marketing_ids']   = $marketing_ids ? implode(',', $marketing_ids) : '';
            $param['money_half_two']  = $money_half_two;  //第二份半价
            $param['people']    = input('people' , 0); //就餐人数;;
            $param['people_child']    = input('people_child' , 0); //就餐人数;;
            $param['people_adult']    = input('people_adult' , 0); //就餐人数;;
            $param['table_num'] = input('table_num' , 0); //餐桌;
            $param['receipt']   = input('receipt'); //发票信息
            $param['remark']    = input('note');//备注
            $param['pay_type']  = $payType;
            $param['source']    = 1;//新平台
            $param['status_order'] = 0;
            $param['status_pay'] = 1;
            $param['type']         = $type ; //堂食
            $param['create_time']  = date('Y-m-d H:i:s' , time() );

            aw_log( ['param' => $param ]  , 'pay_order.log');
            $result = $orderModel->save($param);
            //下单成功
            if ( !$result ) {
                commonServer::error(20004)->exits();
            }

            //增加订单商品信息
            $orderDetailModel = new OrderItem();
            foreach ($orderGoods as $good => $goodVal) {
                $orderGoods[$good]['order_id'] = $result;
            }
            $orderDetailModel->allowField(true)->saveAll( $orderGoods) ;

            if ( $payType == 1 ) {
                //微信支付则调取 小程序微信支付sdk
                $wxPayParam['order_code']  = $orderCode;
                $wxPayParam['total_price'] = $orderPrice;
                $wxPayParam['openid']      = $member_new_info['open_id'];
                $wxPayParam['store_name']  = $storeName;
                $wxPayParam['store_id']    = $storeId;
                $wxPayParam['token']       = $token;
                $payResult = $orderModel->wxpay( $wxPayParam ,  $orderGoods );
                if( !$payResult ){
                    commonServer::error(20004, [], ['input' => Request::instance()->param(), 'output' => $payResult])->exits();
                }
                if( $payResult === true ){
                    $wxpay = 0;
                }
            } else {
                //判断不是微信支付，去支付
                $payResult = $orderModel->pay( $orderCode , $payType  , $goodsNum);
                if( !$payResult ){
                    //支付失败
                    commonServer::error(20004, [], ['input' => Request::instance()->param(), 'output' => $payResult])->exits();
                }
                $wxpay = 0;
                $payResult = [];
            }
            //增加消费记录
            $addLogRes = $orderModel->addOrderLog($orderCode);


            //增加用户消费金额
            $res = $member_server->addUserTotalCost($member_odl_info['member_id'], $orderPrice);
            if ( $res === false ) {
                commonServer::error(20004 , [] , ['input' => Request::instance()->param(),'event'=> 'api/pay/order' , 'func'=> 'addUserTotalCost' ])->exits();
            }

            //发送订单30分钟评价消息
            $orderModel->sendCommonMsg( $result );

            //判断是否使用优惠券，使用则修改优惠券状态
            if( $couponsId ){
                $couponsModel = new Coupons();
                $couponsModel->where( array('coupon_id' => $couponsId ) )->update( ['status_coupon' => 3 ,'time_use' => date('Y-m-d H:i:s' , time())  ]);
            }

            //判断是否有转盘活动
            $wheel_surf = config( 'site.wheel_surf');
            $wheel_surf = $wheel_surf ? $wheel_surf : 0;

            aw_log( ['input' => Request::instance()->param(), 'output' => ['order_code' => $orderCode ,'order_id' => $result , 'wheel_surf'=> $wheel_surf, 'wxpay' => $wxpay, 'wxparam' =>$payResult ] ]  , 'pay_order.log');
            // 提交事务
            // Db::commit();
            //清楚token
            $redis->del( 'order_token_' .$member_info['id']  );

            commonServer::success( ['order_code' => $orderCode ,'order_id' => $result , 'wheel_surf'=> $wheel_surf, 'wxpay' => $wxpay, 'wxparam' =>$payResult ]);
        } catch (\Exception $e) {
            // 回滚事务
            // Db::rollback();

            commonServer::error(20004, [], ['input' => Request::instance()->param(), 'output' => formatErr($e)])->exits();
        }

    }


    //微信支付 回调
    public function notify_url(){

        $key        = input('key');    //小程序密钥
        $order_code = input( 'order_code');
        $admin_key  = input( 'admin_key'); //后台密钥
        $member_server = new memberServer();

        if( $admin_key  ){
            if(  $admin_key != config('admin_key') ){
                commonServer::$showMsg = '密钥不合法';
                commonServer::error(2)->exits();
            }

        } else {
            //验证key合法
            $member_info = $member_server->checkCiphertext($key);
            if ( $member_info === false ) {
                commonServer::$showMsg = '密钥不合法';
                commonServer::error(2)->exits();
            }
        }


        if( !$order_code ){
            commonServer::$showMsg = '订单不存在';
            commonServer::error(2)->exits();
        }
        //延迟2s 防止微信支付异步回调时 当前接口先触发,优先执行微信异步回调
        sleep(2);
        $orderModel = new \app\common\common\model\oldModel\order\order();
        $orderInfo = $orderModel->where(  ['order_code' => $order_code] )->find();
        if( !$orderInfo ){
            commonServer::$showMsg = '订单不存在';
            commonServer::error(2)->exits();
        }
        if( $orderInfo['pay_type'] != 1){
            commonServer::$showMsg = '参数错误';
            commonServer::error(2)->exits();
        }

        aw_log( ['input' => Request::instance()->param(), 'output' => ['order_code' => $order_code ] ]  , 'pay_order_succ.log');

        //判断是否支付成功
        if(  $orderInfo['status_pay'] == 5   ){
            commonServer::success( )->dies();
        }
        

        //去查看微信支付状态
        $url = config('old_url') . '/Home/Member/orderQuery';
        $data['order_code'] = $order_code;
        $res_json = postcurl( $url , $data );
        $res_arr  = json_decode($res_json, true);

        if( $res_arr  && $res_arr['code'] == 0 ){
            if( $res_arr['data']['res']['result_code'] =='SUCCESS'  && $res_arr['data']['res']['return_code'] == 'SUCCESS'  && $orderInfo['pay_type'] == 1 &&  $orderInfo['status_pay'] == 1   ){
                //判断订单状态是否已经支付成功, 未成功的时候 去修改状态
                $result = $orderModel->paySuccess( $order_code );
                if( !$result){
                    commonServer::$showMsg = '修改失败';
                    commonServer::error(2 , [] ,  ['input' => Request::instance()->param(), 'output' => $result] )->exits();
                }
            }
        } else {
            commonServer::$showMsg = '修改失败';
            commonServer::error(2 , [] ,  ['input' => Request::instance()->param(), 'output' => $res_arr] )->exits();
        }


        commonServer::success( )->dies();

    }


}